import axios from "axios";
import qs from 'qs';
import Store from '../store'
import Router from '../router'
import { message, Modal } from 'ant-design-vue';
import apiList from './apiList'
import Loading from "@/components/baseUI/Loading";
import {SHA256} from "@/utils/crypto";
var loadingTimer = null;
var modalDialog = null


const http = (options) => {
    const _options = Object.assign({
        type: "post",        // 请求方式
        url: "",              // 请求地址
        data: {},              // 请求数据
        params: {},            // 请求参数
        headers: {
            'Content-Type':'application/x-www-form-urlencoded'
        },           // 请求头数据
        success: 0,            // 请求成功，从promise resolve返回
        error: 0,               //只要是错误就会执行的方法，不管是状态码错误还是服务器错误，并且也会继续执行后续状态码等错误
        complete: 0,           // 请求结束后的回调函数（无论是否成功都会被调用，不走promise，从参数中调起回调函数）
        loadingIcon: true,     // 是否显示loading状态动画
        loadingText: void 0,
        fastLoading: false,
        noErrMessage: false, //是否有错误提示
        timeout: process.env.NODE_ENV === "development" ? 60000 : 20000,         // 超时时间。默认10000ms
    }, options);

    const axiosInterceptors = axios.interceptors.response.use(response => {
        return response;
    }, error => {
        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = '请求错误';
                    break;
                case 401:
                    error.message = '未授权，请登录';
                    break;
                case 403:
                    error.message = '拒绝访问';
                    break;
                case 404:
                    error.message = `请求地址错误: ` + (_options.url);
                    break;
                case 408:
                    error.message = '请求超时';
                    break;
                case 500:
                    error.message = '服务器内部错误';
                    break;
                case 501:
                    error.message = '服务未实现';
                    break;
                case 502:
                    error.message = '网关错误';
                    break;
                case 503:
                    error.message = '服务不可用';
                    break;
                case 504:
                    error.message = '网关超时';
                    break;
                case 505:
                    error.message = 'HTTP版本不受支持';
                    break
                // no default
            }
        }
        return Promise.reject(error);
    });

    if (_options.loadingIcon) {
        if (_options.fastLoading) {
            clearTimeout(loadingTimer)
            Loading.show( _options.loadingText ? {title: _options.loadingText } : void 0)
        } else {
            clearTimeout(loadingTimer)
            loadingTimer = setTimeout(() => {
                Loading.show( _options.loadingText ? {title: _options.loadingText } : void 0)
            }, 500)
        }
    }

    if(_options.apiType == 'upload') {

    } else {
        _options.data = {
            token: Store.state.user.account.token,
            merNo: Store.state.user.account.merNo,
            ...options.data,
        };

        console.log('0000000000', _options.data);
        if (_options.data.token) {
            console.log('111111111111');
            let newData = {};
            let keyMap = Object.keys(_options.data);
            let fieldMap = {
                a: 1,
                b: 2,
                c: 3,
                d: 4,
                e: 5,
                f: 6,
                g: 7,
                h: 8,
                i: 9,
                j: 10,
                k: 11,
                l: 12,
                m: 13,
                n: 14,
                o: 15,
                p: 16,
                q: 17,
                r: 18,
                s: 19,
                t: 20,
                u: 21,
                v: 22,
                w: 23,
                x: 24,
                y: 25,
                z: 26,
            };
            keyMap.sort(
                (a, b) =>
                    a.slice(0, 1).toLowerCase() -
                    b.slice(0, 1).toLowerCase()
            );
            let signData = ''
            keyMap.forEach((item) => {
                newData[item] = _options.data[item];
                signData += _options.data[item];
            });
            console.log(newData);
            _options.data.sign = SHA256(
                signData + Store.state.user.account.signKey
            );
        }

        if ( _options.headers["Content-Type"] == "application/x-www-form-urlencoded" ) {
            _options.data = qs.stringify(_options.data);
        }
    }

    if(_options.url.indexOf('http') == -1) {
        _options.url = apiList.baseUrl + _options.url
    }


    axios({
        // withCredentials: true,
        method: _options.type,
        url: _options.url,
        headers: _options.headers,
        data: _options.data,
        params: _options.params,
        timeout: _options.timeout
    }).then(res => {
        if (_options.loadingIcon) {
            clearTimeout(loadingTimer)
            Loading.hide()
        }
        var data = res.data;
        axios.interceptors.request.eject(axiosInterceptors);
        if (data.code == 1 || data.code == 1000) {
            typeof _options.success === "function" && _options.success(data);
        }  else if(data.code  == -10001) {
            // 国税登录失效退出
            message.error({
                duration: 2.5,
                content: '登录失效'
            })
        } else if (res.data.code == 10001) {
            if (modalDialog) return;
            modalDialog =  Modal.error({
                title: '登录失效',
                content: '当前账号登录失效，请重新登录',
                onOk: () => {
                    Router.replace('/login/' + (localStorage.merNo || ''))
                    Store.commit('tabs/CLEAR_TABS_LIST')
                    modalDialog = null
                }
            })
            console.log(modalDialog);
            Store.commit('user/CLEAR_USER_ACCOUNT')
        } else {
            typeof _options.success == "function" && _options.error(data)
            if(
                ((typeof _options.noErrMessage == 'number' || typeof _options.noErrMessage == 'string') && _options.noErrMessage == res.data.code) ||
                (Array.isArray(_options.noErrMessage) && _options.noErrMessage.some(i => i == res.data.code)) ||
                (typeof _options.noErrMessage == 'boolean' && _options.noErrMessage)
            ) {
                // 不弹出错误提示
            } else {
                message.error({
                    duration: 2.5,
                    content: data.msg || data.message || '错误'
                })
            }
            console.log(data);
        }
        _options.complete && _options.complete(data);
    }).catch(err => {
        message.error({
            duration: 2.5,
            content: err.message || '错误'
        })
        typeof _options.error === "function" && _options.error(err)
        if (_options.loadingIcon) {
            clearTimeout(loadingTimer)
            Loading.hide()
        }
        _options.complete && _options.complete(err);
    })

}

const request = (options) => {
    return new Promise((resolve, reject) => {
        http({
            ...options,
            success: res => resolve(res),
            error: err => reject(err)
        });
    });
}



export {
    request
}
